//
//  LYPublicViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/30.
//

import UIKit
import AVFoundation

class LYPublicViewController: LYAuthBaseViewController {
    var productId: Int?
    var orderNum: String?
    var onomit: Onomit?
    var titleName: String?
    
    var name: String?
    var IDNum: String?
    var birthday: String?
    
    private let scrollView = UIScrollView()
    private let contentView = UIView()
    let imagePicker = UIImagePickerController()
    
    var imageType: LYStocksManager.ImageType = .frontID
    
    var currentCardData: CardData? = nil
    
    var currentUploadIDCardData: UploadIDCardData? = nil
    
    var clanderAlertView: LYCustomAlertView? = nil
    var idCardAlertView: LYCustomAlertView? = nil
    var customerIDAlertView = LYCustomerIDAlertView()
    
    var idStartTimeStamp: Double = 0.0
    var faceStartTimeStamp: Double = 0.0
    private lazy var aadhaarImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = false
        if appCountryEnv == .indonesia {
            iv.image = UIImage(named: "Aadhaar_bg_id")
        } else {
            iv.image = UIImage(named: "Aadhaar_bg")
        }
        return iv
    }()
    
    lazy var aadhaarButton: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(aadhaarButtonAction(_ :)), for: .touchUpInside)
        return button
    }()

    lazy var faceButton: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(faceButtonAction(_ :)), for: .touchUpInside)
        return button
    }()
    
    private lazy var faceImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = false
        if appCountryEnv == .indonesia {
            iv.image = UIImage(named: "face_bg_id")
        } else {
            iv.image = UIImage(named: "face_bg")
        }
        return iv
    }()
    
    lazy var nextStepButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle(LYlocalizedString("Next step"), for: .normal)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 27.5
        button.addTarget(self, action: #selector(nextStepAction(_ :)), for: .touchUpInside)
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        button.layer.borderWidth = 1.0
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = titleName
        
        commonInitSubviews()
        fetchData()
    }

    func fetchData() { 
        guard let productId = productId else { return }
        LYHUDUtils.showLoading()
        LYStocksManager.fetchCardischoolalityInfo(productId: productId) { [weak self] cardData, msg, error in
            guard let self = self else { return }
            self.currentCardData = cardData
            if error == nil {
                // 身份证
                var isAadhaarCompleted = false
                var isFaceCompleted = false
                if let focusly = cardData?.focusly {
                    if let cardiarium = focusly.cardiarium,
                        cardiarium == 1 { // 身份证完成认证
                        self.aadhaarButton.isEnabled = false
                        isAadhaarCompleted = true
                        if let generationth = focusly.generationth {
                            self.name = generationth.sarcling
                            self.IDNum = generationth.typo
                            self.birthday = generationth.agohood
                        }
                    } else {
                        self.aadhaarButton.isEnabled = true
                    }
                }
                
                if let tremasummerard = cardData?.tremasummerard  {
                    if let cardiarium = tremasummerard.cardiarium,
                        cardiarium == 1 { // 人脸完成认证
                        self.faceButton.isEnabled = false
                        isFaceCompleted = true
                    } else {
                        self.faceButton.isEnabled = true
                    }
                }
                self.updateImageViewConstraints(isAadhaarCompleted: isAadhaarCompleted,
                                                isFaceCompleted: isFaceCompleted)
                LYHUDUtils.hideHUD()
            } else {
                
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func fetchSaveIDCardInfo() {
        
        guard let birthday = self.customerIDAlertView.birthdayClickableView.text,
              birthday.count > 0,
              birthday != "//" else {
            LYHUDUtils.showToast(LYlocalizedString("Birthday"))
            return
        }
        
        LYHUDUtils.showLoading()
        if appCountryEnv == .indonesia {
            LYStocksManager.fetchSaveCardInfo_yinNi(birthday: birthday,
                                                    identifyNum: self.customerIDAlertView.idTextField.textField.text ?? "",
                                                    name: self.customerIDAlertView.nameTextField.textField.text ?? "",
                                                    phoneNum: LYUserDefaults.shared.getString(forKey: phoneNumKey) ?? "",
                                                    orderNum: orderNum ?? "",
                                                    productId: productId ?? -1) { [weak self] succes, msg, error  in
                guard let self = self else { return }
                if error == nil {
                    self.idCardAlertView?.hide()
                    self.updateImageViewConstraints(isAadhaarCompleted: true,
                                                    isFaceCompleted: false)
                    LYTrackingManager.uploadRiskTracking(sceneType: .IdCredential,
                                                         productId: productId,
                                                         orderNum: orderNum,
                                                         startTimeStamp: idStartTimeStamp,
                                                         endTimeStamp: Date().timeIntervalSince1970)
                    LYHUDUtils.hideHUD()
                } else {
                    
                    LYHUDUtils.showToast(msg)
                }
            }
        } else {
            LYStocksManager.fetchSaveCardInfo_yinDu(birthday: birthday,
                                                    identifyNum:  self.customerIDAlertView.idTextField.textField.text ?? "",
                                                    name: self.customerIDAlertView.nameTextField.textField.text ?? "") {[weak self] succes, msg, error  in
                guard let self = self else { return }
                if error == nil {
                    self.idCardAlertView?.hide()
                    self.updateImageViewConstraints(isAadhaarCompleted: true,
                                                    isFaceCompleted: false)
                    LYHUDUtils.hideHUD()
                } else {
                    
                    LYHUDUtils.showToast(msg)
                }
            }
        }
        
    }
    
    func commonInitSubviews() {
        self.view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(aadhaarImageView)
        contentView.addSubview(faceImageView)
        contentView.addSubview(aadhaarButton)
        contentView.addSubview(faceButton)
        self.view.addSubview(nextStepButton)
        
        setLayoutSubviews()
    }
    
    func setLayoutSubviews() {
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalToSuperview().offset(-customTabBarHeight - bottomMargin)
        }
        
        contentView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.width.equalTo(scrollView)
        }
        
        let aspectRatio = 338.0 / 429.0
        let aadhaarWidth = SCREEN_WIDTH - 16 * 2.0
        let aadhaarHeight = aadhaarWidth / aspectRatio
        
        aadhaarImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
            make.width.equalTo(aadhaarWidth)
            make.height.equalTo(aadhaarHeight)
        }
        
        aadhaarButton.snp.makeConstraints { make in
            make.edges.equalTo(aadhaarImageView)
        }
        
        faceImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(aadhaarWidth)
            make.height.equalTo(aadhaarHeight)
            make.top.equalTo(aadhaarImageView.snp.bottom).offset(20)
            make.bottom.equalTo(contentView)
        }
        
        faceButton.snp.makeConstraints { make in
            make.edges.equalTo(faceImageView)
        }
        
        nextStepButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-bottomMargin)
            make.height.equalTo(55)
        }
        
        self.view.layoutIfNeeded()
        scrollView.contentSize = contentView.frame.size
    }
    
    func updateImageViewConstraints(isAadhaarCompleted: Bool, isFaceCompleted: Bool) {
        let aspectRatio = 338.0 / 270.0
        let aadhaarWidth = SCREEN_WIDTH - 16 * 2.0
        let aadhaarHeight = aadhaarWidth / aspectRatio
        
        if isAadhaarCompleted {
            if appCountryEnv == .indonesia {
                aadhaarImageView.image = UIImage(named: "aadhaar_bg_complete_id")
            } else {
                aadhaarImageView.image = UIImage(named: "aadhaar_bg_complete")
            }
            aadhaarImageView.snp.remakeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalToSuperview()
                make.width.equalTo(aadhaarWidth)
                make.height.equalTo(aadhaarHeight)
            }
            
            self.imageType = .portrait
        }

        if isFaceCompleted {
            if appCountryEnv == .indonesia {
                faceImageView.image = UIImage(named: "face_bg_complete_id")
            } else {
                faceImageView.image = UIImage(named: "face_bg_complete")
            }
            faceImageView.snp.remakeConstraints { make in
                make.centerX.equalToSuperview()
                make.width.equalTo(aadhaarWidth)
                make.height.equalTo(aadhaarHeight)
                make.top.equalTo(aadhaarImageView.snp.bottom).offset(20)
                make.bottom.equalTo(contentView)
            }
            
            self.imageType = .unKnown
        }
        
        self.view.layoutIfNeeded()
        scrollView.contentSize = contentView.frame.size
    }

    func checkCameraPermission() {
        if imageType == .portrait {
            faceStartTimeStamp = Date().timeIntervalSince1970
        } else {
            idStartTimeStamp = Date().timeIntervalSince1970
        }
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            openCamera()
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        self.openCamera()
                    } else {
                        print("相机权限被拒绝")
                        self.showNoPermissionAlertView()
                    }
                }
            }
        default:
            self.showNoPermissionAlertView()
        }
    }
    
    func openCamera() {
        guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
            return
        }
        
        imagePicker.sourceType = .camera
        imagePicker.delegate = self // 实现 UIImagePickerControllerDelegate
        imagePicker.allowsEditing = false // 是否允许编辑
        present(imagePicker, animated: true)
        
        if imageType == .portrait {
            imagePicker.cameraDevice = .front
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.hiddeCameraLimitActionView(actionView: self.imagePicker.view)
            }
        }
    }
    
    @objc func nextStepAction(_ sender: UIButton) {
        if self.imageType == .unKnown {
            let publicVC = LYPublicCompletedViewController()
            publicVC.name = self.name
            publicVC.IDNum = self.IDNum
            publicVC.birthday = self.birthday
            publicVC.onomit = self.onomit
            publicVC.productId = self.productId
            publicVC.orderNum = self.orderNum
            self.navigationController?.pushViewController(publicVC, animated: true)
        } else {
            checkCameraPermission()
        }
    }
    
    @objc func faceButtonAction(_ sender: UIButton) {
        checkCameraPermission()
    }
    
    @objc func aadhaarButtonAction(_ sender: UIButton) {
        checkCameraPermission()
    }
    
    func hiddeCameraLimitActionView(actionView: UIView) {
        let name = "CAMFlipButton"
        for view in actionView.subviews {
            if view.description.contains(name) {
                view.isHidden = true
                return
            }
            hiddeCameraLimitActionView(actionView: view)
        }
        
    }
    
    func showNoPermissionAlertView() {
        
        let alert = LYCustomAlertView(
            title: LYlocalizedString(""),
            message: LYlocalizedString("CameraUsageDescription")
        )
        
        let stopBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Stop"),
                                                         actionType: .unObvious)
        
        let turningOnBtn = LYCustomAlertViewAction.getButton(with: LYlocalizedString("Turning on"),
                                                         actionType: .obvious)
        // 添加按钮到弹窗
        alert.addButton(stopBtn) {
            alert.hide()
        }
        
        alert.addButton(turningOnBtn) {
            alert.hide { [weak self] in
                guard let self = self else { return }
                self.openAppSettings()
            }
        }
        
        // 显示弹窗
        alert.show()
    }
    
    func openAppSettings() {
        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString),
              UIApplication.shared.canOpenURL(settingsUrl) else {
            return
        }
        
        UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
    }
}

extension LYPublicViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage {
//            guard let ori = UIImage(named: "photo_indonesia"),
//                  let data = UIImage.compressImage(ori, maxSizeKB: 500) else { return }
            guard let data = UIImage.compressImage(image, maxSizeKB: 500) else { return }
            self.upload(data: data)
            
        }
        picker.dismiss(animated: true)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
    
    func upload(data: Data) {
        LYHUDUtils.showLoading()
        guard imageType != .unKnown else { return }
        LYStocksManager.uploadImage(imageData: data, imageType: self.imageType, imageSource: .camera) { [weak self] cardData, msg, error in
            guard let self = self else { return }
            if error == nil {
                self.currentUploadIDCardData = cardData
                self.showIDCardAlertView()
                
                if self.imageType == .portrait {
                    NotificationCenter.default.post(name: .orderListFollowKey,
                                                    object: nil,
                                                    userInfo: ["customData": self.onomit as Any,
                                                               "orderNum": self.orderNum ?? ""])
                    LYTrackingManager.uploadRiskTracking(sceneType: .faceCredential,
                                                         productId: productId,
                                                         orderNum: orderNum,
                                                         startTimeStamp: faceStartTimeStamp,
                                                         endTimeStamp: Date().timeIntervalSince1970)
                }
                LYHUDUtils.hideHUD()
            } else {
                
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func showIDCardAlertView() {
        guard imageType == .frontID else { return }
        let baseView = LYCustomerIDAlertView()
        if let uploadIDCardData = self.currentUploadIDCardData {
            baseView.setModel(uploadIDCardData: uploadIDCardData)
        }
        let alert = LYCustomAlertView(view: baseView,
                                      backgroundImage: UIImage(named: "account_cancel_bg"))
       
        baseView.confirmActionClosure = {
            self.fetchSaveIDCardInfo()
        }
        
        baseView.birthdayButtonActionClosure = { [weak self] birthday in
            guard let self = self else { return }
            self.showCalendarAlertView(birthday)
        }

        // 显示弹窗
        alert.show()
        self.idCardAlertView = alert
        self.customerIDAlertView = baseView
    }
    
    func showCalendarAlertView(_ dateString: String) {
        var date = stringFormatToDate(dateString: dateString)
        if date == nil {
            date = stringFormatToDate(dateString: "01/01/1990")
        }
        guard let date = date else { return }
        let calendarPicker = LYCalendarPicker(selectedDate: date)
        calendarPicker.delegate = self
        
        let alert = LYCustomAlertView(view: calendarPicker,
                                      backgroundImage: UIImage(named: "account_cancel_bg"))
        alert.show()
        self.clanderAlertView = alert
    }
}

extension LYPublicViewController: LYCalendarPickerDelegate {
    func calendarPicker(_ picker: LYCalendarPicker, didSelectDate date: Date) {
        self.clanderAlertView?.hide()
        
        let dateString = dateToFormatString(date: date)
        self.customerIDAlertView.birthdayClickableView.text = dateString
        self.currentUploadIDCardData?.agohood = dateString
        self.birthday = dateString
    }
}
